package com.daodway.designpattern.statepattern;

import java.util.LinkedList;
import java.util.Queue;

public class MessageDispatcher{
	private static MessageDispatcher instance=null;
	private MessageDispatcher(){
		
	}
	public static MessageDispatcher Instance(){
		if(instance==null){
			instance=new MessageDispatcher();
		}
		return instance;
	}
	private Queue<Telegram> PriorityQ = new LinkedList<Telegram>();
	
	private void Discharge(BaseGameEntity pReceiver,Telegram msg){
		pReceiver.HandleMessage(msg);
	}
	public void DispatchMessage(long delay,long sender,long receiver,int msg,String ExtraInfo){
		BaseGameEntity pReceiver=EntityManager.Instace().getEntityFromId(receiver);
		Telegram telegram=new Telegram(sender, receiver, msg, delay, ExtraInfo);
		if(delay<=0.0){
			Discharge(pReceiver, telegram);
		}else{
			long currentTime=System.currentTimeMillis();
			telegram.DispatchTime=currentTime+delay;
			PriorityQ.add(telegram);
		}
	}
	public void DispatchDelayedMessage(){
		long CurrentTime=System.currentTimeMillis();
			while((PriorityQ.size()>0)&&(PriorityQ.peek().DispatchTime<CurrentTime)&&(PriorityQ.peek().DispatchTime>0)){
				Telegram telegram=PriorityQ.peek();
				BaseGameEntity pReceiver=EntityManager.Instace().getEntityFromId(telegram.Receiver);
				Discharge(pReceiver, telegram);
				PriorityQ.remove(PriorityQ.peek());
			}
	}

}
